const btn = document.getElementById('btn')
const btn2 = document.getElementById('btn2')
const btn3 = document.getElementById('btn3')
const btn4 = document.getElementById('btn4')
const mainImgbox = document.getElementById('mainImgbox')
const box = document.getElementById('box')

btn.addEventListener('click', async () => {
    if (window.electronAPI.isTask()) {
        alert('任务进行中。。。');
        return;
    }
    const filePaths = await window.electronAPI.openFiles()
    mainImgbox.innerHTML = '';
    if (filePaths) {

        filePaths.forEach((url)=>{
            const img = document.createElement('img');
            img.src = url;
            mainImgbox.appendChild(img);
    
        });

        window.electronAPI.mainImg(filePaths)
    };
})

btn2.addEventListener('click', async () => {
    if (window.electronAPI.isTask()) {
        alert('任务进行中。。。');
        return;
    }
    const filePaths = await window.electronAPI.openFiles();
    if(!filePaths || filePaths.length == 0)return;
    window.electronAPI.imgs(filePaths);
    box.innerHTML = '';

    filePaths.forEach((url)=>{
        const img = document.createElement('img');
        img.src = url;
        box.appendChild(img);

    });

    console.log('LPTEXT',filePaths);
})

btn3.addEventListener('click', async () => {
    if (window.electronAPI.isTask()) {
        alert('任务进行中。。。');
        return;
    }
    if( !window.electronAPI.mainImg() || !window.electronAPI.imgs()){
        alert('请选择图片');
        return;
    }
    window.electronAPI.isTask(true);
    console.log('LPTEXT','任务开始');

    const task = await window.electronAPI.TaskStart(window.electronAPI.mainImg(),window.electronAPI.imgs());
    let taskJson=JSON.stringify(task,null,2);
    console.log('LPTEXT',task);
    window.taskJson=taskJson;
    copyToClipboard(taskJson).then(()=>{
        alert('任务完成-数据已复制')
    }).catch((err)=>{
        alert(err)
    });

    window.electronAPI.isTask(false);
    
})

btn4.addEventListener('click', async () => {
    if (window.electronAPI.isTask()) {
        alert('任务进行中。。。');
        return;
    }
    
    console.log('LPTEXT',window.taskJson);
    
    copyToClipboard(window.taskJson).then(()=>{
        alert('任务完成-数据已复制')
    }).catch((err)=>{
        alert(err)
    });

    window.electronAPI.isTask(false);
    
})


function copyToClipboard(textToCopy) {
    // 创建text area
    let textArea = document.createElement("textarea");
    textArea.value = textToCopy;
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = "absolute";
    textArea.style.opacity = 0;
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    return new Promise((res, rej) => {
        // 执行复制命令并移除文本框
        document.execCommand('copy') ? res() : rej();
        textArea.remove();
    });
}